package com.glodon.paas.document.web.service;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.exception.OAuthException;

import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchResponse;
import org.openid4java.message.sreg.SRegMessage;
import org.openid4java.message.sreg.SRegResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.account.sdk.sso.web.AbstractCasSingleSignOnFilter;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.document.biz.ProjectResourceBiz;
import com.glodon.paas.document.service.util.WebService;

/**
 * @author Don Li
 */
public class OpenidLoginCallback extends HttpServlet {
    
    // public static final String USER_INFO = "user_info";
    private static final Logger         LOGGER = LoggerFactory.getLogger(OpenidLoginCallback.class);

    private ConsumerManager             manager;
    private Cas20ServiceTicketValidator serviceTicketValidator;
    private WebService webService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        manager = (ConsumerManager) context.getBean("consumerManager");
        webService = (WebService) context.getBean("webService");
        serviceTicketValidator = (Cas20ServiceTicketValidator) context.getBean("casServiceTicketValidator");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Identifier identifier = verifyResponse(req);
        if (identifier == null) {
            // unsuccess
            resp.getWriter().write("authentication failed");
        } else {
            // exchange access token & secret
            exchangeAccessTokenAndSecret(req);
            // authentication success
            final String email = (String) req.getAttribute("email");
            final String username = (String) req.getAttribute("username");
            final String id = StringUtils.substringAfterLast(identifier.getIdentifier(), "/");
            User user = webService.getUser(id);
//            List<ProjectResourceEntity> resources = resourceBiz.loadUserResource(id);
//            if (user.getPrivileges() == null) {
//                user.setPrivileges(new HashMap<String, Set<String>>());
//            }
//            for (ProjectResourceEntity resource : resources) {
//                if (user.getPrivileges().get(resource.getResource()) == null) {
//                    user.getPrivileges().put(resource.getResource(), new HashSet<String>());
//                }
//                user.getPrivileges().get(resource.getResource()).add(resource.getPrivileges());
//            }
            req.getSession(false).setAttribute(StringConst.USER_INFO, user);
            // redirect to user home
            resp.sendRedirect("file/index#!home/");
        }
    }

    private void exchangeAccessTokenAndSecret(HttpServletRequest req) {
        OAuthProvider provider = (OAuthProvider) req.getSession(false).getAttribute("oauth-provider");
        OAuthConsumer consumer = (OAuthConsumer) req.getSession(false).getAttribute("oauth-consumer");
        if (provider != null && consumer != null) {
            req.getSession(false).removeAttribute("oauth-provider");
            req.getSession(false).removeAttribute("oauth-consumer");
            try {
                provider.retrieveAccessToken(consumer, null);
                LOGGER.info("access token: {}", consumer.getToken());
                LOGGER.info("token secret: {}", consumer.getTokenSecret());
                // TODO store the access token & secret for future usage
            } catch (OAuthException e) {
                LOGGER.error("can't exchange request token to access token", e);
            }
        }
    }

    public Identifier verifyResponse(HttpServletRequest httpReq) throws IOException {
        try {
            ParameterList response = new ParameterList(httpReq.getParameterMap());

            DiscoveryInformation discovered = (DiscoveryInformation) httpReq.getSession(false).getAttribute("openid-discovered");

            // extract the receiving URL from the HTTP request
            StringBuffer receivingURL = httpReq.getRequestURL();
            String queryString = httpReq.getQueryString();
            if (queryString != null && queryString.length() > 0) {
                receivingURL.append("?").append(httpReq.getQueryString());
            }

            LOGGER.debug("Receive URL: {}", receivingURL.toString());

            // verify the response
            VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);

            LOGGER.debug("Verify finished");

            // examine the verification result and extract the verified identifier
            Identifier verified = verification.getVerifiedId();

            if (verified != null) {
                AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

                if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
                    SRegResponse sRegResponse = (SRegResponse) authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);
                    sRegResponse.getAttributeValue("fullname");
                }

                if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                    FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
                    String email = fetchResp.getAttributeValueByTypeUri("email");
                    String username = fetchResp.getAttributeValueByTypeUri("username");
                    httpReq.setAttribute("email", email);
                    httpReq.setAttribute("username", username);
                }

                String serviceTicket = httpReq.getParameter("st");
                LOGGER.debug("retrieve service ticket : {}", serviceTicket);

                if (verifyServiceTicket(serviceTicket, httpReq)) {
                    return verified; // success
                }
            }
        } catch (OpenIDException e) {
            LOGGER.error("OpenID Verification Error", e);
        }
        return null;
    }

    private boolean verifyServiceTicket(String ticket, HttpServletRequest request) {
        if (StringUtils.isBlank(ticket)) {
            return false;
        } else {
            try {
                Assertion assertion = serviceTicketValidator.validate(ticket, "document");
                LOGGER.info("ST validation succeed for user {}", assertion.getPrincipal().getName());
                request.getSession(false).setAttribute(AbstractCasSingleSignOnFilter.CAS_ASSERTION, assertion);
                request.getSession(false).setAttribute(AbstractCasSingleSignOnFilter.CAS_SERVICE_TICKET, ticket);
                return true;
            } catch (TicketValidationException e) {
                LOGGER.error("ST validation error", e);
            }
        }
        return false;
    }
}
